# # -*- coding: utf-8 -*-
# # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models,fields, _
from odoo.exceptions import ValidationError


class ResUsers(models.Model):
    _inherit = "res.users"
    # smtp_id=fields.Many2one('ir.mail_server',string='发件服务器')
    smtp_pa=fields.Char('你的邮箱密码')

    # def __init__(self, pool, cr): #其实在view中的字段属性 readonly='0'
    #     init_res = super(ResUsers, self).__init__(pool, cr)
    #     # duplicate list to avoid modifying the original reference
    #     type(self).SELF_WRITEABLE_FIELDS = type(self).SELF_WRITEABLE_FIELDS + ['smtp_pa']
    #     type(self).SELF_READABLE_FIELDS = type(self).SELF_READABLE_FIELDS + ['smtp_pa']
    #     return init_res

    @api.multi
    def write(self, values):
        pa=values.get('smtp_pa',False)
        # if pa:
        #     del values['smtp_pa']  #不需要录入到res.users.smtp_pa,而且也无法保存
        if pa:
            self.SELF_WRITEABLE_FIELDS.append('smtp_pa') #源码中判断这个列表存在可以修改，否则不可以修改。所以加上这个以便修改
        super(ResUsers, self).write(values) #修改res.users的ir.model.access perm_write=True
        if pa:  #如果有密码修改就创建mail_server(smtp_server)
            email = self.email
            mail_server_obj = self.env['ir.mail_server']
            mail_server = mail_server_obj.sudo().search([('smtp_user', '=', email)])
            if mail_server:
                mail_server.update(
                    {'smtp_pass':pa}
                )
                # mail_server.test_smtp_connection() #测试outgoing mail server 连接成功否 ,但是不能返回修改的记录
            else:
                mail_server = mail_server_obj.sudo().create(
                    {
                        'name': self.partner_id.name,
                        'smtp_host': 'smtp.' + email[email.index('@') + 1:],
                        'smtp_port': 25,
                        'smtp_pass': pa,
                        'smtp_user': email
                    }
                )
            return mail_server

    @api.multi
    def test_smtp_connection(self):
        email=self.env.user.email
        mail_server=self.env['ir.mail_server'].sudo().search([('smtp_user', '=', email)])
        if mail_server:
            mail_server.test_smtp_connection()
        return





